<template>
  <div class="layout home">
    <Layout class="page-index-main">
      <Sider class="main-sider">
        <Layout>
          <Header class="main-sider-header">
            <span>Unistar {{user.version}}</span>
          </Header>
          <Content>
            <Menu ref="menu" :active-name="menu" :open-names="openedSubs" width="auto" @on-select="onMenuSelect">
              <template v-for="(m,i) in menus">
                <MenuItem v-if="!m.childList||m.childList.length===0" :name="m.route" :to="m.route" replace>
                <Icon :type="m.icon" /><span>{{m.name}}</span>
                </MenuItem>
                <Submenu v-else-if="m.childList&&m.childList.length>0" :name="m.route">
                  <template slot="title">
                    <Icon :type="m.icon" /> {{m.name}}
                  </template>
                  <MenuItem v-for="(mc,j) in m.childList" :key="j" :name="mc.route" :to="mc.route" replace>
                  <Icon :type="mc.icon" /><span>{{mc.name}}</span>
                  </MenuItem>
                </Submenu>
              </template>
            </Menu>
          </Content>
        </Layout>
      </Sider>
      <Layout class="main-body">
        <Header class="main-body-header">
          <Row>
            <Col span="12">
            <span v-if="canChangeNs">
              {{$t('header.namespace')}}：
              <Button type="text" @click="nsChoosing=true">
                {{currentNs}}
                <Icon size="14" type="ios-switch" />
              </Button>
            </span>&nbsp;</Col>
            <Col span="12" class="right">
            <Poptip v-model="userShowing" placement="bottom-end">
              <Avatar class="cursor-pointer" @click="userShowing=true">{{user.nick.charAt(0)}}</Avatar>
              <div class="header-right-content" slot="content">
                <div class="header-right-inner-content">
                  <div class="header-right-user-popover-content">
                    <div class="header-right-user-popover-title">{{user.nick}}</div>
                    <div class="header-right-user-popover-text">{{user.email}}</div>
                    <div class="header-right-user-popover-button-group">
                      <Button type="primary" @click="changePassword">
                        <span>{{ $t('header.user.changepass') }}</span>
                        <div class="header-right-user-ripple-wrapper"></div>
                      </Button>
                      <Button @click="onLogout">
                        <span>{{ $t('header.user.exit') }}</span>
                        <div class="ant-ripple-wrapper"></div>
                      </Button>
                    </div>
                  </div>
                </div>
              </div>
            </Poptip>
            </Col>
          </Row>
        </Header>
        <Content class="main-body-container">
          <router-view></router-view>
        </Content>
      </Layout>
    </Layout>
    <Drawer :title="nsChooseTitle" :closable="false" v-model="nsChoosing">
      <Form :label-width="0">
        <FormItem>
          <CompNschoose :current="currentNs" :disall="true" @onChosen="changeChosenNs" />
        </FormItem>
        <FormItem class="center">
          <Button @click="nsChoosing=false">{{$t('button.cancel')}}</Button>
          <Button type="primary" style="margin-left: 8px" @click="changeNamespace">{{$t('button.confirm')}}</Button>
        </FormItem>
      </Form>
    </Drawer>
    <Drawer :title="passChangingTitle" :closable="!forcePassChange" :mask-closable="!forcePassChange" v-model="passChanging">
      <Form ref="changepassForm" :label-width="0" :model="passform" :rules="passFormRules">
        <FormItem prop="oldpass">
          <Input v-model="passform.oldpass" type="password" password :placeholder="$t('form.inputrule', [$t('changepass.oldpass')])">
          <Icon type="ios-lock-outline" slot="prepend"></Icon>
          </Input>
        </FormItem>
        <FormItem prop="newpass">
          <Input v-model="passform.newpass" type="password" password :placeholder="$t('form.inputrule', [$t('changepass.newpass')])">
          <Icon type="ios-lock-outline" slot="prepend"></Icon>
          </Input>
        </FormItem>
        <FormItem class="center">
          <Button type="primary" long @click="changePass">{{$t('button.confirm')}}</Button>
        </FormItem>
      </Form>
    </Drawer>
  </div>
</template>

<script>
  import CompNschoose from '@/components/nschoose'
  const G_MENUS = require('@/api/data/menu').default
  let id = 0
  export default {
    name: 'console',
    components: { CompNschoose },
    watch: {
      $route(to) {
        let path = to.path
        this.menu = path
        this.$nextTick(() => { this.$refs.menu.updateOpened() })
        if (path.indexOf('/base/') === 0
          || path.indexOf('/system/') === 0
          || path.indexOf('/user/') === 0) {
          this.canChangeNs = false
        } else {
          this.canChangeNs = true
        }
        this.findOpenedSubs(path)
      }
    },
    data() {
      return {
        openedSubs: [],
        theme: 'light',
        canChangeNs: false,
        nsChoosing: false,
        menu: '',
        menus: [],
        user: {
          nick: '',
          email: '',
          inited: true,
          version: '',
        },
        userShowing: false,
        currentNs: '',
        chosenNs: '',
        forcePassChange: true,
        passChanging: false,
        passform: {
          oldpass: '',
          newpass: '',
        },
        passFormRules: {
          oldpass: [
            { required: true, message: this.$t('changepass.validate.need', [this.$t('changepass.oldpass')]), trigger: 'blur' },
            { type: 'string', min: 6, message: this.$t('changepass.validate.complex'), trigger: 'blur' }
          ],
          newpass: [
            { required: true, message: this.$t('changepass.validate.need', [this.$t('changepass.newpass')]), trigger: 'blur' },
            { type: 'string', min: 6, message: this.$t('changepass.validate.complex'), trigger: 'blur' }
          ],
        }
      }
    },
    computed: {
      nsChooseTitle() {
        return this.$t('header.nsChoosing')
      },
      passChangingTitle() {
        return this.$t('header.passChanging')
      }
    },
    created() {
      let user = this.$storage.getUser()
      if (!user) return
      this.user.nick = user.nick
      this.user.email = user.email
      this.user.inited = user.inited
      this.user.version = user.version
      if (!this.user.inited) {
        // 没有初始化过的，则强制修改密码
        this.passChanging = true
      }
      //
      this.menu = this.$router.currentRoute.path
      this.menus = this.resolveMenu()
      this.findOpenedSubs(this.$route.path)
      this.currentNs = this.$storage.getNamespace()
      this.chosenNs = this.currentNs
      this.changeNamespace()
    },
    methods: {
      onLogout() {
        this.$storage.delUser()
        this.$router.push('/login')
      },
      changeChosenNs(ns) {
        this.chosenNs = ns
      },
      changeNamespace() {
        this.$md.changeNamespace(this.chosenNs)
        this.$storage.setNamespace(this.chosenNs)
        if (this.currentNs === this.chosenNs) return
        window.location.reload()
      },
      resolveMenu() {
        let that = this
        let retMenus = []
        // ====================================
        // 解析菜单
        // ====================================
        let resolve = (contains, menus) => {
          menus.forEach(menu => {
            // 检测用户是否有角色权限
            if (!that.$storage.checkUserRole(menu.role)) return
            !menu.id && (menu.id = ++id)
            menu.name = menu.name || that.$t(menu.lang)
            if (!menu.route) menu.route = 'level-' + menu.id
            if (!menu.icon) menu.icon = menu.childList ? 'ios-browsers' : 'md-reorder'
            contains.push(menu)
            // ====================================
            // 解析子菜单
            if (menu.childList) {
              let childList = menu.childList
              menu.childList = []
              resolve(menu.childList, childList)
            } else {
              menu.childList = []
            }
          })
        }
        resolve(retMenus, G_MENUS)
        return retMenus
      },
      onMenuSelect(menu) {
        this.menu = menu
      },
      findOpenedSubs(path) {
        this.openedSubs = this.genOpenSubs(path, this.menus)
      },
      genOpenSubs(route, menus) {
        let subs = []
        let findSubs = (val, menus) => {
          let found = false
          if (val === '/') return found
          menus.forEach(menu => {
            if (menu.childList && menu.childList.length > 0) {
              if (findSubs(val, menu.childList)) subs.push(menu.route)
            } else if (menu.route === route) {
              found = true
            }
          })
          return found
        }
        findSubs(route, menus)
        return subs
      },
      changePassword() {
        this.userShowing = false
        this.passChanging = true
        this.forcePassChange = false
      },
      changePass() {
        this.$refs.changepassForm.validate(valid => {
          if (valid) {
            this.$md.dispatch('changepass', this.passform).then(data => {
              if (data.retCode === 1) {
                this.onLogout()
              } else {
                this.$Message.error(this.$t(data.retMsg, [this.$t('changepass.oldpass')]))
              }
            })
          }
        })
      }
    }
  };
</script>

<style scoped lang="less">
  .layout {
    position: relative;
    background: #f5f7f9;
    height: inherit;
  }

  .home {
    min-height: 100vh;
    overflow: auto;

    .layout-header-bar {
      background: #f8f8f9;
      box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
    }

    .main-sider {
      height: 100vh;
      left: 0;
      background: #ffffff;

      .main-sider-header {
        color: #17233d;
        background: #ffffff;
        padding: 10px 20px;

        img {
          width: 32px;
          height: 32px;
          border-radius: 50%;
        }

        span {
          font-size: 22px;
          font-weight: 600;
          height: 32px;
          line-height: 32px;
          display: inline-block;
          width: 69px;
          text-overflow: ellipsis;
          white-space: nowrap;
          vertical-align: text-bottom;
        }
      }

      i {
        vertical-align: middle;
        font-size: 18px;
      }
    }

    .main-body {
      .main-body-header {
        background: #f8f8f9;
        padding: 0 15px;

        .header-right-user-popover-title {
          font-weight: 700;
          font-size: 18px;
          text-align: center;
          color: #000;
          margin: 12px 0;
        }

        .header-right-user-popover-title {
          font-weight: 700;
          font-size: 18px;
          color: #000;
          margin: 12px 0;
        }
        .header-right-user-popover-text {
          font-size: 13px;
          color: #000;
          line-height: 20px;
          margin-top: 4px;
        }
        .header-right-user-popover-button-group {
          margin-top: 20px;
          white-space: nowrap;
          .v-btn {
            height: 32px;
            background-color: #fff;
          }
        }
      }

      .main-body-container {
        padding: 0 15px 15px 15px;
      }
    }
  }
</style>
